package cn.nfwx.tv.okhttp;

import com.alibaba.fastjson.support.retrofit.Retrofit2ConverterFactory;

import cn.nfwx.tv.conts.Constants;
import okhttp3.Call;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class Http {
    private final String TAG = Http.class.getSimpleName();

    Retrofit mRetrofit;

    private static Http instance;

    public static Http getInstance() {
        if (instance == null) {
            synchronized (Http.class) {
                if (instance == null) {
                    instance = new Http();
                }
            }
        }
        return instance;
    }

    public Http() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(Constants.ijk_url)
                .client(CustomOkHttpClient.getOkHttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(new Retrofit2ConverterFactory())
                .build();
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }

    /**
     * 多个http的链接切换
     *
     * @param service
     * @param <T>
     * @return
     */
    public <T> T getLiveRetrofit(final Class<T> service) {
        return getRetrofit().newBuilder().baseUrl(Constants.ijk_url_live).build().create(service);
    }

    /**
     * 多个http的链接切换
     *
     * @param service
     * @param <T>
     * @return
     */
    public <T> T getNyqfRetrofit(final Class<T> service) {
        return getRetrofit().newBuilder().baseUrl(Constants.ijk_url).build().create(service);
    }

    /**
     * @param service
     * @param <T>
     * @return
     */
    public <T> T getCommentRetrofit(final Class<T> service) {
        return getRetrofit().newBuilder().baseUrl(Constants.ijk_url).build().create(service);
    }

    /**
     * 取消
     *
     * @param tag
     */
    public static void cancleAll(Object tag) {
        if (tag == null) {
            return;
        }
        Call.Factory callFactory = getInstance().getRetrofit().callFactory();
        if (callFactory instanceof OkHttpClient) {
            Dispatcher dispatcher = ((OkHttpClient) callFactory).dispatcher();
            for (Call call : dispatcher.queuedCalls()) {
                if (tag.equals(call.request().tag())) {
                    call.cancel();
                }
            }
            for (Call call : dispatcher.runningCalls()) {
                if (tag.equals(call.request().tag())) {
                    call.cancel();
                }
            }
        }
    }
}
